import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { KnowledgeDoc, KnowledgeQuery } from '@/api/knowledge'
import {
  getKnowledgeDocs,
  getKnowledgeDoc,
  createKnowledgeDoc,
  updateKnowledgeDoc,
  deleteKnowledgeDoc,
  getKnowledgeCategories,
  getPopularDocs,
} from '@/api/knowledge'

export const useKnowledgeStore = defineStore('knowledge', () => {
  // State
  const documents = ref<KnowledgeDoc[]>([])
  const currentDocument = ref<KnowledgeDoc | null>(null)
  const categories = ref<string[]>([])
  const popularDocs = ref<KnowledgeDoc[]>([])
  const loading = ref(false)
  const pagination = ref({
    total: 0,
    page: 1,
    pageSize: 10,
  })

  // Query params
  const queryParams = ref<KnowledgeQuery>({
    search: '',
    category: '',
    tags: [],
    status: 'published',
    page: 1,
    pageSize: 10,
  })

  // Computed
  const hasMore = computed(() => {
    return documents.value.length < pagination.value.total
  })

  // Actions
  const fetchDocuments = async (params?: Partial<KnowledgeQuery>) => {
    try {
      loading.value = true

      // Merge with existing query params
      const mergedParams = {
        ...queryParams.value,
        ...params,
      }

      const response = await getKnowledgeDocs(mergedParams)

      documents.value = (response.data || []).map((doc: any) => ({
        ...doc,
        id: doc.id || doc._id, // Ensure id is set
        likeCount: doc.likeCount || doc.helpfulCount || 0, // Map likeCount
      }))

      pagination.value = {
        total: response.pagination?.total || 0,
        page: response.pagination?.current || mergedParams.page || 1,
        pageSize: response.pagination?.pageSize || mergedParams.pageSize || 10,
      }

      // Update query params
      queryParams.value = mergedParams

      return documents.value
    } catch (error) {
      console.error('Failed to fetch documents:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchDocumentById = async (id: string) => {
    try {
      loading.value = true
      const doc = await getKnowledgeDoc(id)
      currentDocument.value = {
        ...doc,
        id: doc.id || (doc as any)._id,
      }
      return currentDocument.value
    } catch (error) {
      console.error('Failed to fetch document:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const createDocument = async (data: {
    title: string
    content: string
    category: string
    tags?: string[]
    status?: string
  }) => {
    try {
      loading.value = true
      const doc = await createKnowledgeDoc(data)
      documents.value.unshift({
        ...doc,
        id: doc.id || (doc as any)._id,
      })
      pagination.value.total += 1
      return doc
    } catch (error) {
      console.error('Failed to create document:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateDocument = async (id: string, data: {
    title?: string
    content?: string
    category?: string
    tags?: string[]
    status?: string
  }) => {
    try {
      loading.value = true
      const doc = await updateKnowledgeDoc(id, data)

      // Update in list
      const index = documents.value.findIndex(d => d.id === id || (d as any)._id === id)
      if (index !== -1) {
        documents.value[index] = {
          ...doc,
          id: doc.id || (doc as any)._id,
        }
      }

      // Update current document
      if (currentDocument.value && (currentDocument.value.id === id || (currentDocument.value as any)._id === id)) {
        currentDocument.value = {
          ...doc,
          id: doc.id || (doc as any)._id,
        }
      }

      return doc
    } catch (error) {
      console.error('Failed to update document:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteDocument = async (id: string) => {
    try {
      loading.value = true
      await deleteKnowledgeDoc(id)

      // Remove from list
      documents.value = documents.value.filter(d => d.id !== id && (d as any)._id !== id)
      pagination.value.total -= 1

      // Clear current document if it's the deleted one
      if (currentDocument.value && (currentDocument.value.id === id || (currentDocument.value as any)._id === id)) {
        currentDocument.value = null
      }
    } catch (error) {
      console.error('Failed to delete document:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchCategories = async () => {
    try {
      const response = await getKnowledgeCategories()
      categories.value = Array.isArray(response.data) ? response.data : []
      return categories.value
    } catch (error) {
      console.error('Failed to fetch categories:', error)
      categories.value = []
      return []
    }
  }

  const fetchPopularDocs = async () => {
    try {
      const response = await getPopularDocs()
      const docs = response.data || []
      popularDocs.value = docs.map((doc: any) => ({
        ...doc,
        id: doc.id || doc._id,
      }))
      return popularDocs.value
    } catch (error) {
      console.error('Failed to fetch popular docs:', error)
      popularDocs.value = []
      return []
    }
  }

  const search = async (searchText: string) => {
    queryParams.value.search = searchText
    queryParams.value.page = 1 // Reset to first page
    return await fetchDocuments()
  }

  const filterByCategory = async (category: string) => {
    queryParams.value.category = category === 'all' ? '' : category
    queryParams.value.page = 1
    return await fetchDocuments()
  }

  const filterByTags = async (tags: string[]) => {
    queryParams.value.tags = tags
    queryParams.value.page = 1
    return await fetchDocuments()
  }

  const changePage = async (page: number) => {
    queryParams.value.page = page
    return await fetchDocuments()
  }

  const changePageSize = async (pageSize: number) => {
    queryParams.value.pageSize = pageSize
    queryParams.value.page = 1
    return await fetchDocuments()
  }

  const resetFilters = async () => {
    queryParams.value = {
      search: '',
      category: '',
      tags: [],
      status: 'published',
      page: 1,
      pageSize: 10,
    }
    return await fetchDocuments()
  }

  return {
    // State
    documents,
    currentDocument,
    categories,
    popularDocs,
    loading,
    pagination,
    queryParams,

    // Computed
    hasMore,

    // Actions
    fetchDocuments,
    fetchDocumentById,
    createDocument,
    updateDocument,
    deleteDocument,
    fetchCategories,
    fetchPopularDocs,
    search,
    filterByCategory,
    filterByTags,
    changePage,
    changePageSize,
    resetFilters,
  }
})
